import logging
import os
from datetime import datetime
from logging.handlers import RotatingFileHandler

DEFAULT_LOG_PATH = "./logs"
DEFAULT_LOG_FORMAT = "[%(levelname)s] [%(asctime)s] [%(module)s] [%(funcName)s] [line:%(lineno)d]: %(message)s"
DEFAULT_DATEFMT = '%Y-%m-%d %H:%M:%S'


def get_mylogger(name, level=logging.INFO, log_path=None, log_format=None, datefmt=None,is_console=False):
    """
    为每个爬虫创建独立的logger
    :param name: 爬虫名称
    :param level: 日志级别
    :param log_path: 日志文件路径
    :param log_format: 日志格式
    :param datefmt: 日期格式
    :return: logger实例
    """
    # 创建logger
    logger = logging.getLogger(name)

    # 如果logger已经有处理器，说明已经初始化过，直接返回
    if logger.handlers:
        return logger

    # 设置日志级别
    logger.setLevel(level)

    # 设置日志路径
    if log_path is None:
        log_path = os.getenv("LOG_PATH", DEFAULT_LOG_PATH)

    # 创建日志目录
    try:
        if not os.path.exists(log_path):
            os.makedirs(log_path, mode=0o755, exist_ok=True)
    except Exception as e:
        print(f"Failed to create log directory: {e}")
        raise

    # 创建日志文件
    current_date = datetime.now().strftime('%Y-%m-%d')
    log_file = os.path.join(log_path, f"{name}_{current_date}.log")

    # 创建文件处理器
    fh = RotatingFileHandler(
        log_file,
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    fh.setLevel(level)

    # 设置日志格式
    if log_format is None:
        log_format = DEFAULT_LOG_FORMAT
    if datefmt is None:
        datefmt = DEFAULT_DATEFMT
    formatter = logging.Formatter(log_format, datefmt=datefmt)
    fh.setFormatter(formatter)

    # 添加处理器到logger
    logger.addHandler(fh)

    # 添加控制台处理器（可选）
    if is_console:
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        logger.addHandler(ch)

    return logger
